<script>
import { getEnterpriseListApi, delEnterpriseApi, queryBuildList, addRecentApi, getRentListApi, rentOutApi } from '@/api/enterprise'
import { uploadFile } from '@/api/common'
import { mapState } from 'vuex';
export default {
  name: 'Enterprise',
  data() {
    return {
      // 企业列表
      enterpriseList: [],
      // 分页
      page: {
        pageSize: 3,
        page: 1,
        name: ''
      },
      total: 0,
      queryString: '',
      rentDialogVisible: false,
      permission:[],
      rentForm: {
        buildingId: null, // 楼宇id
        contractId: null, // 合同id
        contractUrl: '', // 合同Url
        enterpriseId: null, // 企业名称
        type: 0, // 合同类型
        rentTime: [] // 合同时间
      },
      buildList: [],
      rentRules: {
        buildingId: [
          { required: true, message: '请选择楼宇', trigger: 'change' }
        ],
        rentTime: [
          { required: true, message: '请选择租赁日期', trigger: 'change' }
        ],
        contractId: [
          { required: true, message: '请上传合同文件' }
        ]
      }
    }
  },
  created() {
    this.getEnterpriseList()
    this.getBuild()
    // console.log(this.profile)
    this.permission = this.profile.permissions
    
  },
  computed:{
    ...mapState('permission',['profile'])
  },
  
  methods: {
    // 计算序号
    indexMethod(index) {
      return (this.page.currentPage - 1) * this.page.pageSize + index + 1
    },
    // 获取企业列表
    async getEnterpriseList() {
      const { data } = await getEnterpriseListApi({
        pageSize: this.page.pageSize,
        page: this.page.page,
        name: this.page.name
      })
      this.enterpriseList = data.rows.map((item) => {
        return {
          ...item,
          rentList: []
        }
      })
      this.total = data.total
    },
    // 分页
    handleCurrentChange(val) {
      this.page.page = val
      console.log(val)
      this.getEnterpriseList()
    },
    search() {
      this.page.currentPage = 1
      this.getEnterpriseList()
    },
    addEnterprise() {
      this.$router.push('/addEnterprise')
    },
    toEditPage(id) {
      this.$router.push({ path: '/addEnterprise', query: { id: id }})
    },
    delEnterprise(id) {
      this.$confirm('是否删除该企业？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delEnterpriseApi(id).then((res) => {
          this.$message.success('删除成功')
          this.getEnterpriseList()
          if (this.enterpriseList.length === 1 && this.page.page !== 1) {
            this.page.page--
          }
        })
      }).catch(() => {
        console.log('取消')
      })
    },
    addRent(id) {
      this.rentDialogVisible = true
      this.rentForm.enterpriseId = id
    },
    closeDialog() {
      console.log(1)
      this.rentDialogVisible = false
      this.$refs.addForm.resetFields()
      this.rentForm = {
        buildingId: null, // 楼宇id
        contractId: null, // 合同id
        contractUrl: '', // 合同Url
        enterpriseId: null, // 企业名称
        type: 0, // 合同类型
        rentTime: [] // 合同时间
      }
      console.log(this.rentForm)
      this.$refs.upload.clearFiles()
    },
    getBuild() {
      queryBuildList().then((res) => {
        this.buildList = res.data
      })
    },
    beforeUpload(file) {
      const isLt5M = file.size / 1024 / 1024 < 5
      if (!isLt5M) {
        this.$message.error('上传文件大小不能超过 5MB!')
        return isLt5M
      }
      const fileType = ['application/msword', 'application/pdf', 'application/docx']
      if (!fileType.includes(file.type)) {
        this.$message.error('上传文件格式不正确')
        return false
      }
    },
    uploadFileFn({ file }) {
      const formData = new FormData()
      formData.append('file', file)
      formData.append('type', 2)
      uploadFile(formData).then((res) => {
        this.rentForm.contractId = res.data.id
        this.rentForm.contractUrl = res.data.url
      })
    },
    handleExceed() {
      console.log(1)
      this.$message.error('只能上传一个文件')
    },
    addHetong(id) {
      this.$refs.addForm.validate(async valid => {
        if (valid) {
          const { buildingId, contractId, contractUrl, enterpriseId, type } = this.rentForm
          await addRecentApi({
            buildingId, contractId, contractUrl, enterpriseId, type,
            startTime: this.rentForm.rentTime[1],
            endTime: this.rentForm.rentTime[1]
          }).then((res) => {
            if (res) {
              this.$message.success(res.msg)
              this.getEnterpriseList()
              this.closeDialog()
            }
          })
        }
      })
    },
    uploadRemoveFn() {
      this.addForm.contractUrl = ''
      this.addForm.contractId = ''
    },
    tableTexpand(row, expandRows) {
      // 判断当前行是否展开
      const isInclude = expandRows.find(item => item.id === row.id)
      if (!isInclude) {
        return
      } else {
        getRentListApi(row.id).then((res) => {
          row.rentList = res.data
        })
      }
    },
    formateStatus(status) {
      const Map = {
        0: '未生效',
        1: '生效中',
        2: '已过期',
        3: '已退租'
      }
      return Map[status]
    },
    formatInfoType(status) {
      const Map = {
        0: 'warning',
        1: 'success',
        2: 'info',
        3: 'danger'
      }
      return Map[status]
    },
    rentOut(id) {
      this.$confirm('是否退租？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await rentOutApi(id)
        this.$message.success('退租成功')
        this.getEnterpriseList()
      }).catch(() => {
        console.log('取消')
      })
    },
    toEnterpriseDetail(id) {
      this.$router.push({ path: '/exterpriseDetail', query: { id: id }})
    }
  }
}
</script>
<template>
  <div class="building-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <div class="search-label">企业名称：</div>
      <el-input v-model="page.name" clearable placeholder="请输入内容" class="search-main" @clear="search" />
      <el-button type="primary" @click="search">查询</el-button>
    </div>
    <div class="create-container">
      <el-button type="primary" @click="addEnterprise" v-permission="'park:enterprise:add_edit'">添加企业</el-button>
    </div>
    <!-- 表格区域 -->
    <div class="table">
      <el-table style="width: 100%" :data="enterpriseList" :index="indexMethod" @expand-change="tableTexpand">
        <el-table-column type="expand">
          <template #default="scoped">
            <el-table :data="scoped.row.rentList">
              <el-table-column label="租赁楼宇" width="320" prop="buildingName" />
              <el-table-column label="租赁起始时间" prop="startTime">
                <template #default="rentObj">
                  {{ rentObj.row.startTime }} -- {{ rentObj.row.endTime }}
                </template>
              </el-table-column>
              <el-table-column label="合同状态" prop="status">
                <template #default="rentObj">
                  <el-tag :type="formatInfoType(rentObj.row.status)">
                    {{ formateStatus(rentObj.row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="180">
                <template #default="scope">
                  <el-button size="mini" type="text" @click="rentOut(scope.row.id)" :disabled="scoped.row.status === 3">退租</el-button>
                  <el-button size="mini" type="text">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>
        <el-table-column type="index" label="序号" />
        <el-table-column label="企业名称" width="320" prop="name" />
        <el-table-column label="联系人" prop="contact" />
        <el-table-column
          label="联系电话"
          prop="contactNumber"
        />
        <el-table-column label="操作">
          <template #default="scope">
            <el-button size="mini" type="text" @click="addRent(scope.row.id)">添加合同</el-button>
            <el-button size="mini" type="text" @click="toEnterpriseDetail(scope.row.id)">查看</el-button>
            <el-button size="mini" type="text" @click="toEditPage(scope.row.id)">编辑</el-button>
            <el-button size="mini" type="text" @click="delEnterprise(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="page-container">
      <el-pagination

        background
        layout="total, prev, pager, next"
        :total="total"
        :page-size="page.pageSize"
        @current-change="handleCurrentChange"
      />
    </div>
    <el-dialog
      title="添加合同"
      :visible="rentDialogVisible"
      width="580px"
      @close="closeDialog"
    >
      <!-- 表单区域 -->
      <!-- 表单模版 -->
      <div class="form-container">
        <el-form ref="addForm" :model="rentForm" :rules="rentRules" label-position="top">
          <el-form-item label="租赁楼宇" prop="buildingId">
            <el-select v-model="rentForm.buildingId" placeholder="请选择">
              <el-option
                v-for="item in buildList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="租赁起止日期" prop="rentTime">
            <el-date-picker
              v-model="rentForm.rentTime"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
            />
          </el-form-item>
          <el-form-item label="租赁合同" prop="contractId">
            <el-upload
              ref="upload"
              action="#"
              :multiple="false"
              :drag="true"
              :before-upload="beforeUpload"
              :http-request="uploadFileFn"
              :limit="1"
              :on-exceed="handleExceed"
              :on-remove="uploadRemoveFn"
            >
              <el-button size="small" type="primary" plain>上传合同文件</el-button>
              <div slot="tip" class="el-upload__tip">支持扩展名：.doc .docx .pdf, 文件大小不超过5M</div>
            </el-upload>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button size="mini" @click="closeDialog">取 消</el-button>
        <el-button size="mini" type="primary" @click="addHetong">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.department-container {
  padding: 10px;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, .9);
  ;
  padding-bottom: 20px;

  .search-label {
    width: 100px;
  }

  .search-main {
    width: 220px;
    margin-right: 10px;
  }
}
.create-container{
  margin: 10px 0px;
}
.page-container{
  padding:4px 0px;
  text-align: right;
}
.form-container{
  padding:0px 80px;
}
</style>
